﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using WebDAVSharp.Server;
using WebDAVSharp.Server.Stores.BaseClasses;

namespace AzureStorageLight
{
    public class AppWebDavStoreItem : WebDavStoreItemBase
    {
        protected StorageItemManager Service
        {
            get
            {
                if (_service == null)
                {
                    _service = StorageItemManager.CreateStorageItemManager(StorageConfig.Instance);
                }
                return _service;
            }
        }
        private StorageItemManager _service;

        internal StorageItem Item
        {
            get
            {
                if (_blobItem == null) EnsuteItem().Wait();
                return _blobItem;
            }

        }
        private StorageItem _blobItem;

        public async Task EnsuteItem()
        {
            if (_blobItem == null)
            {
                var parent = StorageItemUtil.GetParent(this.ItemPath);
                var datalist = Service.GetFiles(parent);
                var data = datalist.OrderBy(x => x.Type).ThenBy(x => x.Name).ToList();
                _blobItem = data.FirstOrDefault(x => x.Name == StorageItemUtil.GetFileName(this.ItemPath));
            }
            await Task.Delay(0);
        }


        public override string ItemPath
        {
            get
            {
                return base.Name;
            }
        }

        public new bool IsCollection
        {
            get
            {
                return base.Name.EndsWith("/");
            }
        }

        public AppWebDavStoreItem(AppWebDavStoreCollection parentCollection, string path)
            : base(parentCollection, path)
        {
        }
    }
}
